//
//  BiBaseNetEngine.m
//  TrunkIndustryManageSystem
//
//  Created by bindu on 15-4-7.
//  Copyright (c) 2015年 李璐西. All rights reserved.
//

#import "BiBaseNetEngine.h"
#import "BiNetEngine.h"
#import "ASINetworkQueue.h"
#import "ASIFormDataRequest.h"

@implementation BiBaseNetEngine

- (id)init
{
    if (self = [super init])
    {
        _networkQueue = [[ASINetworkQueue alloc] init];
        [_networkQueue setDelegate:self];
        [_networkQueue setRequestDidFinishSelector:NSSelectorFromString(@"requestDone:")];
        [_networkQueue setRequestDidFailSelector:NSSelectorFromString(@"requestFaild:")];
        
        _dataDic = [[NSMutableDictionary alloc] init];
    }
    
    return self;
}

- (void)dealloc
{
    [_networkQueue cancelAllOperations];
    [_networkQueue reset];
    [_networkQueue release];
    
    _RELEASE(_dataDic)
    
    [super dealloc];
}

- (NSString *)urlEncodeValue:(NSString *)str
{
    NSString *result = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, NULL, kCFStringEncodingUTF8);
    return [result autorelease];
}

- (ASIFormDataRequest *)createPostRequest:(NSString *)url_ paramDic:(NSDictionary*)paramDic tag:(int)tag
{
    NSString *url = [self urlEncodeValue:url_];
    
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setRequestMethod:@"POST"];
    [request addRequestHeader:@"Connection" value:@"keep-alive"];
    
    if (nil != paramDic)
    {
        for (int i = 0; i < paramDic.allKeys.count; i++)
        {
            [request addPostValue:[paramDic objectForKey:[paramDic.allKeys objectAtIndex:i]] forKey:[paramDic.allKeys objectAtIndex:i]];
        }
    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSString stringWithFormat:@"%d",tag] forKey:@"t_tag"];
    [request setUserInfo:userInfo];
    [request setTimeOutSeconds:SERVICE_TIMEOUT];
    [_networkQueue addOperation:request];
    
    [_networkQueue go];
    NSLog(@"%@     tag:%d", url_, tag);
    
    return [request autorelease];
}

- (ASIFormDataRequest *)createPostImageRequest:(NSString *)url_ image:(UIImage*)image tag:(int)tag
{
    NSString *url = [self urlEncodeValue:url_];
    
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setRequestMethod:@"POST"];
    [request addRequestHeader:@"Connection" value:@"keep-alive"];
    [request addRequestHeader:@"Accept-Encoding" value:@"gzip, deflate"];
    [request addRequestHeader:@"Content-Type" value:@"multipart/form-data"];
    
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    NSString * imageFileName = [BiUtil getSendTmpFileName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:imageFileName])
    {
        [fileManager removeItemAtPath:imageFileName error:nil];
    }
    
    [imageData writeToFile:imageFileName atomically:YES];
    [request addPostValue:@"1" forKey:@"type"];
    [request setFile:imageFileName forKey:@"body"];
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSString stringWithFormat:@"%d",tag] forKey:@"t_tag"];
    [request setUserInfo:userInfo];
    
    [request setTimeOutSeconds:SERVICE_TIMEOUT];
    [_networkQueue addOperation:request];
    
    NSLog(@"%@     tag:%d", url_, tag);
    [_networkQueue go];
    
    return [request autorelease];
}

- (ASIHTTPRequest *)createGetRequest:(NSString *)url_ paramDic:(NSDictionary*)paramDic tag:(int)tag
{
    NSString *url = [self urlEncodeValue:url_];
    
    if (nil != paramDic)
    {
        if (paramDic.allKeys.count > 0)
        {
            NSMutableString * mutableString = [NSMutableString stringWithFormat:@"?"];
            
            for (int i = 0; i < paramDic.allKeys.count; i++)
            {
                NSString * key = [paramDic.allKeys objectAtIndex:i];
                NSString * value = [paramDic objectForKey:[paramDic.allKeys objectAtIndex:i]];
                [mutableString appendFormat:@"%@=%@&", key, value];
            }
            
            NSString * paramString = [mutableString substringToIndex:(mutableString.length-1)];
            url = [NSString stringWithFormat:@"%@%@", url, paramString];
        }
    }
    
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:url]];
    request.useCookiePersistence = YES;
    [request setRequestMethod:@"GET"];
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSString stringWithFormat:@"%d",tag] forKey:@"t_tag"];
    [request setUserInfo:userInfo];
    [request setTimeOutSeconds:SERVICE_TIMEOUT];
    [_networkQueue addOperation:request];
    
    [_networkQueue go];
    return [request autorelease];
}

//    *****************      网络处理      *****************
#pragma mark ASI Request
-(void)requestFaild:(ASIHTTPRequest *)request
{
    int tag = [[[request userInfo] objectForKey:@"t_tag"] intValue];
    NSLog(@"%@---tag: %d",[[request error] description], tag);
    
    id delegate = [_dataDic objectForKey:[NSNumber numberWithInt:tag]];
    [_dataDic removeObjectForKey:[NSNumber numberWithInt:tag]];  // 请求完后清除掉delegate
    
    if (nil != delegate && [delegate respondsToSelector:@selector(onNetEngineResponseFail:entity:userInfo:)])
    {
        [delegate onNetEngineResponseFail:tag entity:nil userInfo:nil];
    }
}

- (void)requestDone:(ASIHTTPRequest *)request
{
    assert(0);
}

@end
